<?php
class uformsHelper
{

    private $fpfix = 'fxt_';

    /**
     * 验证定义,等同与formvalid.js
     * @param  [type] $type [description]
     * @return [type]       [description]
     */
    public function getValids($k = null)
    {
        $r = array(
            'isString'  => '字符串',
            'isNumber'  => '数字',
            'isEmail'   => '邮件',
            'isPhone'   => '电话',
            'isMobile'  => '手机',
            'isIdCard'  => '身份证',
            'isMoney'   => '货币',
            'isZip'     => '邮编',
            'isQQ'      => 'QQ',
            'isInt'     => '整数',
            'isEnglish' => '英文',
            'isChinese' => '中文',
            'isUrl'     => '网址',
            'isDate'    => '日期',

        );

        return $k ? $r[$k] : $r;
    }

    /**
     * 字段类型
     * @return [type] [description]
     */
    public function getFieldType($tp = null)
    {
        $tps = array(
            'input'    => '单行输入',
            'textarea' => '多行输入',
            'checkbox' => '多选框',
            'radio'    => '单选框',
            'select'   => '下拉框',
            'editor'   => '编辑器',
            'date'     => '日期输入框',
            'pic'      => '图片上传',
        );
        return $tp ? $tps[$tp] : $tps;

    }
    /**
     * 获取扩展字段
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function getExtFields($id, $ext_w = null)
    {
        $w[]         = ["f_id", "=", $id];
        $w[]         = ["delete_time", "=", "0"];
        $ext_w && $w = array_merge($w, $ext_w);
        $r           = \think\facade\Db::name("forms_field")->field("t_field_id,concat('" . $this->fpfix . "',t_field_id) as t_field_key,t_field_name,t_field_value,t_field_type,t_field_source,t_field_valid,t_field_err,t_field_other,t_field_fill,t_field_order,t_field_sys,if(t_field_fshow,'yes','no') as f_css,t_field_smsg,t_field_fshow,t_field_css")->order("t_field_order asc")->where($w)->select()->toArray();
        $r           = array_column($r, null, 't_field_id');
        return $r;
    }

    /**
     * [getExtFieldsHtml description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function getExtFieldsHtml($id, $values = null,$ext_w=null,$wrap=1)
    {

        $rows = $this->getExtFields($id,$ext_w);

        foreach ($rows as &$v) {
            //验证规则
            $vds       = array();
            $valid_ext = null;
            $valids    = null;
            if ($v['t_field_fill']) {
                $vds['required'] = $v['t_field_name'] . '不能是空值';
            }

            if ($v['t_field_valid']) {

                $valid_ext = $v['t_field_valid'] == 'custom' ? "custom='custom_function_" . $v['t_field_id'] . "'" : '';

                $vds[$v['t_field_valid']] = $v['t_field_err'] ? $v['t_field_err'] : $v['t_field_name'] . '必须是' . $this->getValids($v['t_field_valid']) . '格式';
            }
            if ($vds) {
                $valids = " lay-verify='" . implode('|', array_keys($vds)) . "' errmsg='" . implode('|', array_values($vds)) . "' " . $valid_ext . "";
            }

            $rule = array(
                'name'        => 'ext[' . $this->fpfix . $v['t_field_id'] . ']',
                'id'          => $this->convert2Id('ext[' . $this->fpfix . $v['t_field_id'] . ']'),
                'value'       => $values[$this->fpfix . $v['t_field_id']] ? $values[$this->fpfix . $v['t_field_id']] : $v['t_field_value'],
                'data'        => $this->getDataSource($v['t_field_source']),
                'css'         =>  $v['t_field_css'],
                'valid'       => $valids,
                'memo'        => $v['t_field_memo'],
                'other'       => $v['t_field_other'],
                'placeholder' => '请输入' . $v['t_field_name'],
            );
            $v['t_field_html'] = $this->FieldHtml($v['t_field_type'], $rule,$wrap);

        }
        return $rows;
    }

    public function FieldHtml($tp, $cfg,$wrap)
    {
               

        if (method_exists($this, $tp . 'Html')) {
            $html =  call_user_func_array(array("self", $tp . 'Html'), array('cfg' => $cfg));
        } else {
            $html =  $this->inputHtml($cfg);
        }
        if($wrap){
            $wrap_css = in_array($tp, array('editor','pic','checkbox','radio'))?'layui-input-block':'layui-input-inline';
            $html = sprintf("<div class='%s'>%s</div>",$wrap_css,$html);

            
        }
        return $html;
    }

    /**
     * input html
     * @param  [type] $cfg [description]
     * @return [type]      [description]
     */
    public function inputHtml($cfg)
    {

        return "<input type='text' " . $cfg['valid'] . " " . $cfg['other'] . " id='" . $cfg['id'] . "'  name='" . $cfg['name'] . "' value='" . $cfg['value'] . "' class='layui-input " . $cfg['css'] . "'   placeholder='" . $cfg['placeholder'] . "' />" . $cfg['memo'];
    }
/**
 * input html
 * @param  [type] $cfg [description]
 * @return [type]      [description]
 */
    public function textareaHtml($cfg,$flag=0)
    {
        return "<textarea id='" . $cfg['id'] . "'  " . $cfg['valid'] . " " . $cfg['other'] . "  name='" . $cfg['name'] . "'    class='" . ($flag==0?"layui-textarea":"ueditors") . "' >" . $cfg['value'] . "</textarea>" . $cfg['memo'];
    }

    /**
     * radio html
     * @param  [type] $cfg [description]
     * @return [type]      [description]
     */
    public function radioHtml($cfg)
    {
        $r = [];
        $t = count($cfg['data']);
        $i = 0;
        foreach ($cfg['data'] as $v) {

            $seld = $cfg['value'] == $v ? 'checked=checked' : '';
            $i++;
            if ($i == $t) {
                $str = $cfg['valid'] . ' ' . $cfg['other'];
            }

            $r[] = '<input type="radio" ' . $seld . ' name="' . $cfg['name'] . '" value="' . $v . '" class="' . $cfg['css'] . '"   ' . $str . ' title="' . $v . '" />';
        }

        return implode(' ', $r) . $cfg['memo'];
    }

    /**
     * checkbox html
     * @param  [type] $cfg [description]
     * @return [type]      [description]
     */
    public function checkboxHtml($cfg)
    {


        $r = [];
        $t = count($cfg['data']);
        $i=0;
        //保存的值
        $items = explode("\n",$cfg['value']);
        foreach($cfg['data'] as $v){
            $seld =  in_array($v, $items)?  'checked=checked':'';
            $i++;
            if($i==$t) $str = $cfg['valid'].' '.$cfg['other'];
            $r[] = '<input type="checkbox" '.$seld.' name="'.$cfg['name'].'[]" value="'.$v.'" class="'.$cfg['css'].'"  '.$str.' title="'.$v.'" />';
        }
        return implode(' ',$r).$cfg['memo'];
    }

    /**
     * select html
     * @param  [type] $cfg [description]
     * @return [type]      [description]
     */
    public function selectHtml($cfg)
    {
        $r_fir = '<select name="' . $cfg['name'] . '[]"  rel="' . $cfg['value'] . '"  class="' . $cfg['css'] . '" lay-filter="' . $cfg['css'] . '"  ' . $cfg['valid'] . ' ' . $cfg['other'] . '  >';
        $r[]   = '<option value="">请选择</option>';
        foreach ($cfg['data'] as $v) {
            $seld = $cfg['value'] == $v ? 'selected=selected' : '';
            $r[]  = '<option ' . $seld . ' value="' . $v . '"> ' . $v . ' </option>';
        }
        return $r_fir . implode('\n', $r) . '</select>' . $cfg['memo'];
    }

    /**
     * [editorHtml description]
     * @param  [type] $cfg [description]
     * @return [type]      [description]
     */
    public function editorHtml($cfg)
    {
        $r = $this->textareaHtml($cfg,1);
        return $r;
    }
/**
 * [date description]
 * @param  [type] $cfg [description]
 * @return [type]      [description]
 */
    public function dateHtml($cfg)
    {
        $html = "<input type='text' class='layui-input laydates'    " . $cfg['valid'] . " " . $cfg['other'] . "  name='" . $cfg['name'] . "' value='" . $cfg['value'] . "'    />" . $cfg['memo'];   
        return $html;
    }

    /**
     * [picHtml description]
     * @return [type] [description]
     */
    public function picHtml($cfg)
    {
        $id    = $cfg['id'];
        $reval = "";
        $reval .= " <div class='layui-col-md2'><input name=\"" . $cfg['name'] . "\"   placeholder=\"图片地址\" value=\"" . $cfg['value'] . "\" class=\"layui-input ajax_file_input\">\n";
        $reval .= "</div><div class='layui-col-md3' style='padding-left:10px;'>  \n";
        $reval .= "\n";
        $reval .= " <button type=\"button\" class=\"layui-btn layui-btn-primary ajax_file\"   >\n";
        $reval .= "                    <i class=\"layui-icon\">&#xe67c;</i>上传图片\n";
        $reval .= "                  </button>\n";
        $reval .= "                  </div>\n";

        return $reval;

    }

    /**
     * [convert2Id description]
     * @return [type] [description]
     */
    public function convert2Id($name)
    {
        return str_replace(array('[', ']'), array('_', ''), $name);
    }

    /**
     * [getFieldDataSource description]
     * @return [type] [description]
     */
    public function getDataSource($from)
    {

        switch (substr($from, 0, strpos($from, ':'))) {
            case 'func:':
                # code...
                $pm = json_decode(substr($from, strpos($from, ':')));
                if (method_exists($pm['method'])) {
                    $r = call_user_func_array($pm['method'], $pm['args']);
                } else {
                    $r = array();
                }
                break;
            case 'json:':
                # code...
                $r = json_decode(substr($from, strpos($from, ':')));
                break;

            default:
                $r = json_decode(str_replace("\r", "", $from));
                break;
        }
        return $r;
    }

    /**
     * 表单类型
     * @return [type] [description]
     */
    public function ftypes($key = null)
    {
        $r = array('1' => '通用表单', '2' => '活动表单', '3' => '预约表单');
        return $key ? $r[$key] : $r;
    }

    /**
     * 订单状态
     * @param  [type] $t [description]
     * @return [type]    [description]
     */
    public function formStatues($t)
    {
        $status = array(0 => '未处理', 1 => '跟进中', 2 => '已完成');
        return $t ? $status[$t] : $status;
    }

}
